const BaseRest = require('./rest.js');

module.exports = class extends BaseRest {
	async getAction() {
		let data = {};
		const map = {};
		// 获取详情
		if(this.id) {
			map.id = this.id;
			data = await this.modelInstance.where(map).find();
			return this.success(data);
		}
		
		// 关键词
		const key = this.get('key');
		if(key) {
			map['name|title|description'] = ['like', '%' + key + '%'];
		}
		
		// 页码
		const page = this.get('page') || 0;
		
		if(page > 0) {
			// 每页显示数量
			const pageSize = this.get('pageSize') || 10;
			
			// think.logger.debug(map);
			
			data = await this.modelInstance.where(map).page(page, pageSize).order('id asc').countSelect();
			return this.success(data);
		} else {
			// 不分页
			data = await this.modelInstance.where(map).order('id asc').select();
			return this.success(data);
		}
	}
	
	/**
	 * 删除内容
	 * @return {[type]} [description]
	 */
	async deleteAction() {
		if(!this.id) {
			return this.fail(1001, '记录不存在');
		}
		
		// 删除用户授权的角色信息
		if(this.get('uid')) {
			const uid = this.get('uid');
			
			const rows = await this.model('user_role').where({
				uid: uid, role_id: this.id
			}).delete();
			if(rows) {
				await  this.hook('authRuleUpdate');
				return this.success({
					affectedRows: rows
				}, '删除成功');
			} else {
				return this.fail(1000, '删除失败');
			}
		}
		
		// 需要处理成事物，保证信息一致
		// 删除角色关联信息
		const rows1 = await this.model('user_role').where({
			role_id: this.id
		}).delete();
		// 删除角色
		const rows = await this.modelInstance.where({
			id: this.id
		}).delete();
		if(rows) {
			// await this.hook('roleDelete', {id: this.id});
			await  this.hook('authRuleUpdate');
			
			return this.success({
				affectedRows: rows
			}, '删除成功');
		} else {
			return this.fail(1000, '删除失败');
		}
	}
	
	async postAction() {
		const data = this.post();
		data['parent_id'] = 1; //默认角色权限分配
		
		data['deletable'] =1;
		data['update_time']=data['create_time']= Math.round((new Date()).getTime() / 1000);
		
		// 将角色授权给用户
		if(this.post('role_id') && this.post('uid')) {
			const exists = await this.model('user_role').where({
				uid: this.post('uid'),
				role_id: this.post('role_id')
			}).count() > 0;
			if(exists) {
				return this.fail(1000, '角色已经授权，不能重复授权');
			} else {
				const id = await this.model('role').addUser(this.post('role_id'), this.post('uid'));
				if(id) {
					await  this.hook('authRuleUpdate');
					return this.success({id: id}, '添加成功');
				} else {
					return this.fail(1000, '添加失败');
				}
			}
		}
		
		delete data['id'];
		
		if(await this.modelInstance.where({name: data['name']}).count() > 0) {
			//已经存在
			return this.fail(1000, '角色已经存在，添加失败');
		} else {
			// 增加角色操作
			const id = await this.modelInstance.add(data);
			if(id) {
				await  this.hook('authRuleUpdate');
				return this.success({id: id}, '添加成功');
			} else {
				return this.fail(1000, '添加失败');
			}
		}
	}
};
